package com.ash.socketb.dual;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 客户端连接方式
 * 1. 客户端可以使用telnet工具进行连接
 * 2. 自己写socket客户端连接
 */
public class ServerDualDemo {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8081);

        // 这个设置对以下方法会有影响，如果项accept永不超时，则不设置
        // ServerSocket.accept()
        //SocketInputStream.read()
        //DatagramSocket.receive()
        //serverSocket.setSoTimeout(5000);

        do {
            Socket oneConnect = serverSocket.accept();
            oneConnect.setSoTimeout(10000);
            System.out.println("有客户来了:" + oneConnect);

            handleConnect(oneConnect);

        } while (true);

    }

    /**
     * 可以使用异步处理，这里主要是演示功能，不做异步处理方式。简化案例复杂度
     *
     * @param accept
     * @throws IOException
     */
    private static void handleConnect(Socket accept) {
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
             OutputStream outputStream = accept.getOutputStream()
        ) {

            StringBuilder requestPayload = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
                requestPayload.append(line);
            }

            // 处理响应
            outputStream.write(requestPayload.toString().getBytes(StandardCharsets.UTF_8));
//            outputStream.flush();
//            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
